﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using BackupAssurance.Library.ModelsDB;
using BackupAssurance.expDB.EF;
using BackupAssurance.Library.DBEF;

using System.ComponentModel.Composition;


namespace BackupAssurance.expDB
{

    [Export(typeof(IdoEF))]
    [PartCreationPolicy(CreationPolicy.Shared)]
    public class expDataIO : IdoEF
    {
        //MainContext db;

        public expDataIO()
        {
            //constructor
            using (var db = new MainContext())
            {
                Database.SetInitializer(new MainContextInitializer());
            }

        }

        public string updateJobActionNextRunTime(pcJobAction objJobAction, DateTime nextrundatetime)
        {
            string result;

            using (var db = new MainContext())
            {

                try
                {
                    db.JobActions.Attach(objJobAction);
                    objJobAction.LastUpdated = DateTime.Now;
                    objJobAction.RunTimeNext = nextrundatetime;
                    db.Entry(objJobAction).Property(u => u.RunTimeNext).IsModified = true;
                    db.Entry(objJobAction).Property(u => u.LastUpdated).IsModified = true;
                    db.SaveChanges();
                    result = "";
                }
                catch (Exception ex)
                {

                    result = ex.Message + Environment.NewLine + ex.StackTrace;
                }
            }

            return result;
        }

        public void addAuditLog(string strDescription, string strName, int iTypeId, long iJobActionID, string strResult)
        {
            using (var db = new MainContext())
            {
                pcAuditLog objAudit = new pcAuditLog();
                objAudit.DateActualRun = DateTime.Now;
                objAudit.DateCreated = DateTime.Now;
                objAudit.description = strDescription;
                objAudit.ErrorTypeId = iTypeId;
                objAudit.name = strName;
                objAudit.pcJobActionId = iJobActionID;
                objAudit.Result = strResult;
                db.Audits.Add(objAudit);
                db.SaveChanges();
            }
        }

        public string updateRunNowFlag(pcJobAction objJobAction, DateTime runlasttime)
        {
            string result;

            using (var db = new MainContext())
            {

                try
                {
                    db.JobActions.Attach(objJobAction);
                    objJobAction.RunNow = false;
                    db.Entry(objJobAction).Property(u => u.RunNow).IsModified = true;
                    db.SaveChanges();
                    result = "";
                }
                catch (Exception ex)
                {

                    result = ex.Message + Environment.NewLine + ex.StackTrace;
                }
            }

            return result;
        }

        public string updateJobActionLastRun(pcJobAction objJobAction, DateTime runlasttime)
        {
            string result;

            using (var db = new MainContext())
            {

                try
                {
                    db.JobActions.Attach(objJobAction);
                    objJobAction.LastUpdated = DateTime.Now;
                    objJobAction.RunTimeLast = DateTime.Now;
                    db.Entry(objJobAction).Property(u => u.RunTimeNext).IsModified = true;
                    db.Entry(objJobAction).Property(u => u.LastUpdated).IsModified = true;
                    db.SaveChanges();
                    result = "";
                }
                catch (Exception ex)
                {

                    result = ex.Message + Environment.NewLine + ex.StackTrace;
                }
            }

            return result;
        }

        public List<pcPlugInValue> Getplugins(long JobActionId)
        {
            using (var db = new MainContext())
            {
                var items = from plg in db.PlugIns
                            where plg.pcJobActionId == JobActionId
                            orderby plg.ExecuteOrder ascending
                            select plg;

                return items.ToList<pcPlugInValue>();
            }
        }

        public List<pcPlugInValue> GetAllplugins(string strServerName)
        {
            using (var db = new MainContext())
            {

                var items = from plg in db.PlugIns
                            join ja in db.JobActions on plg.pcJobActionId equals ja.Id
                            where ja.JobEnabled == 1 && ja.ServerName == strServerName && ja.StartDate <= DateTime.Now && ja.EndDate >= DateTime.Now
                            select plg;

                return items.ToList<pcPlugInValue>();
            }
        }

        public List<pcJobAction> getJobActions(string strServerName)
        {
            using (var db = new MainContext())
            {

                var item = from ja in db.JobActions
                           where ja.JobEnabled == 1 && ja.ServerName == strServerName && ja.StartDate <= DateTime.Now && ja.EndDate >= DateTime.Now
                           select ja;

                return item.ToList<pcJobAction>();

                //                using (var context = new UnicornsContext()) {  
                //                    // Load all unicorns from the database into the context
                //                    context.Unicorns.Load();    
                //                    // Add a new unicorn to the context   
                //                    context.Unicorns.Add(new Unicorn { Name = "Linqy" });  
                //                    // Mark one of the existing unicorns as Deleted   
                //                    context.Unicorns.Remove(context.Unicorns.Find(1));
                //                    // Loop over the unicorns in the context.  
                //                    Console.WriteLine("In Local: ");   
                //                    foreach (var unicorn in context.Unicorns.Local)     {   
                //                        Console.WriteLine("Found {0}: {1} with state {2}",   unicorn.Id, unicorn.Name, context.Entry(unicorn).State);     
                //                    } 

                //                    // Perform a query against the database.     
                //                    Console.WriteLine("" + Environment.NewLine + "In DbSet query: ");     
                //                    foreach (var unicorn in context.Unicorns)     {         
                //                        Console.WriteLine("Found {0}: {1} with state {2}",unicorn.Id, unicorn.Name,context.Entry(unicorn).State);     } 
                //                }
                //using (var context = new UnicornsContext()) {     
                //    // Load some unicorns from the database into the context     
                //    context.Unicorns.Where(u => u.Name.StartsWith("B")).Load();       
                //    // Get the local collection and make some changes to it     
                //    var localUnicorns = context.Unicorns.Local;     
                //    localUnicorns.Add(new Unicorn { Name = "Linqy" });
                //    localUnicorns.Remove(context.Unicorns.Find(1));       
                //    // Loop over the unicorns in the context.     
                //    Console.WriteLine("In Local: ");     
                //    foreach (var unicorn in context.Unicorns.Local)     {         
                //        Console.WriteLine("Found {0}: {1} with state {2}",unicorn.Id, unicorn.Name,  context.Entry(unicorn).State);     
                //    }     var unicorn1 = context.Unicorns.Find(1);   
                //    Console.WriteLine("State of unicorn 1: {0} is {1}",unicorn1.Name, context.Entry(unicorn1).State);
                //    // Query some more unicorns from the database 
                //    context.Unicorns.Where(u => u.Name.EndsWith("py")).Load(); 
                //    // Loop over the unicorns in the context again.    
                //    Console.WriteLine("" + Environment.NewLine + "In Local after query: ");   
                //    foreach (var unicorn in context.Unicorns.Local)     {  
                //        Console.WriteLine("Found {0}: {1} with state {2}", unicorn.Id, unicorn.Name, context.Entry(unicorn).State); 
                //    } 
                //}

                //    using (var context = new UnicornsContext()) { 

                //    // Load some entities into the context     
                //    context.Unicorns.Include(u => u.Princess.LadiesInWaiting).Load();      
                //    // Make some changes     
                //    context.Unicorns.Add(new Unicorn { Name = "Linqy" });     
                //    context.Unicorns.Remove(context.Unicorns.Find(1));     
                //    context.Princesses.Local.First().Name = "Belle";     
                //    context.LadiesInWaiting.Local.First().Title = "Special";      
                //    // Look at the state of all entities in the context     
                //    Console.WriteLine("All tracked entities: ");     
                //    foreach (var entry in context.ChangeTracker.Entries())     
                //    {         Console.WriteLine("Found entity of type {0} with state {1}",                     
                //        ObjectContext.GetObjectType(entry.Entity.GetType()).Name,                     
                //        entry.State);     }      
                //    // Find modified entities of any type     
                //    Console.WriteLine("" + Environment.NewLine + "All modified entities: ");     
                //    foreach (var entry in context.ChangeTracker.Entries()                               
                //        .Where(e => e.State == EntityState.Modified))     {
                //        Console.WriteLine("Found entity of type {0} with state {1}",               
                //            ObjectContext.GetObjectType(entry.Entity.GetType()).Name,              
                //            entry.State);     }     
                //    // Get some information about just the tracked princesses   
                //    Console.WriteLine("" + Environment.NewLine + "Tracked princesses: ");    

                //    foreach (var entry in context.ChangeTracker.Entries<Princess>())     {  
                //        Console.WriteLine("Found Princess {0}: {1} with original Name {2}",  
                //            entry.Entity.Id, entry.Entity.Name,                        
                //            entry.Property(p => p.Name).OriginalValue);     }  
                //    // Find any person (lady or princess) whose name starts with 'S'   
                //    Console.WriteLine("" + Environment.NewLine + "People starting with 'S': ");  
                //    foreach (var entry in context.ChangeTracker.Entries<IPerson>()  
                //        .Where(p => p.Entity.Name.StartsWith("S")))     {     
                //        Console.WriteLine("Found Person {0}", entry.Entity.Name);     } } 



                // Load one princess and her related unicorns     
                //var princess1 = context.Princesses                         
                //    .Where(p => p.Name == "Cinderella")                         
                //    .Include(p => p.Unicorns)                         
                //    .FirstOrDefault();  //or  .ToList(); 

                // pcPlugInValue
                //var MixData = from ja in db1.JobActions
                //                 from pcdm in db1.DriveMounts
                //                 where ja.JobEnabled == 1 && ja.pcDriveMountId == pcdm.Id
                //                 select new { MountDriveId = pcdm.Id, MountDriveName= pcdm.name, pcdm.ServerName , 
                //pcdm.ServerIP , pcdm.DriveLetter , pcdm.UserAccount, pcdm.UserPassword  ,pcdm.FileFolder};
                //
                //result = MixData.ToString();
                //public override int SaveChanges() {     foreach (var unicorn in this.Unicorns.Local.ToList())   
                //{         if (unicorn.Princess == null)       
                //{             this.Unicorns.Remove(unicorn);  
                //}     }     
                //return base.SaveChanges(); }

                //var princess = context.Princesses.Find(1);  
                // Count how many unicorns the princess owns  
                //var unicornHaul = context.Entry(princess)     
                //    .Collection(p => p.Unicorns)           
                //    .Query()                         
                //    .Count(); 

                // Load the unicorns starting with B related to a given princess   
                //context.Entry(princess)    
                //    .Collection(p => p.Unicorns) 
                //    .Query()       
                //    .Where(u => u.Name.StartsWith("B"))  
                //    .Load();   
                // Load the unicorns starting with B related to a given princess 
                // using a string to specify the relationship  
                //context.Entry(princess)      
                //    .Collection("Unicorns")   
                //    .Query().Cast<Unicorn>()  
                //    .Where(u => u.Name.StartsWith("B"))   
                //    .Load(); 

                // Load all castles, all related ladies-in-waiting, and all related princesses 
                //var castles1 = context.Castles 
                //    .Include(c => c.LadiesInWaiting.Select(b => b.Princess))  
                //    .ToList();  
                // Load all unicorns, all related princesses,                 and all related ladies   
                //var unicorns1 = context.Unicorns              
                //    .Include(u => u.Princess.LadiesInWaiting) 
                //    .ToList(); 
                // Load all castles, all related ladies, and all related princesses  
                // using a string to specify the relationships   
                //var castles2 = context.Castles          
                //    .Include("LadiesInWaiting.Princess") 
                //    .ToList(); 
                //var unicorn = context.Unicorns.Find(1); 

                //var princess = context.Princesses.Find(2); 


                //MixData.
                //MixData.AsEnumerable().ToDictionary(o => o.MountDriveId);
                //db1.DriveMounts.AsEnumerable().ToDictionary(
                //Context.EntitySetName.AsEnumerable().ToDictionary(o => o.Key, o => o.Value); 


                //public List<Customer> FindCustomerList(string companyName)
                //{
                //    var q = from c in context.Customers
                //            where c.CompanyName.StartsWith(companyName)
                //            select c;
                //    return q.ToList();
                //}

                //public Customer FindCustomer(string customerID)
                //{
                //    var q = from c in context.Customers //.Include("Orders")
                //            where c.CustomerID == customerID
                //            select c;
                //    var customer = q.First();
                //    return customer;
                //}

                //public void UpdateCustomer(Customer customer)
                //{
                //    context.Attach(customer);
                //    //context.ObjectStateManager.GetObjectStateEntry(customer.EntityKey).SetModified();
                //    customer.SetAllModified(context); // custom extension method

                //    try
                //    {
                //        context.SaveChanges();
                //    }
                //    catch (OptimisticConcurrencyException e)
                //    {
                //        //context.Refresh(RefreshMode.ClientWins, customer); // Last in wins
                //        //context.SaveChanges();
                //        throw (e);
                //    }
                //}

                //public void AddCustomer(Customer customer)
                //{
                //    context.AddToCustomers(customer);
                //    context.SaveChanges();
                //}

                //public void DeleteCustomer(Customer customer)
                //{
                //    context.Attach(customer);
                //    context.DeleteObject(customer);
                //    context.SaveChanges();
                //}



                //var MixData = from u in db.JobActions
                //where u.Name.StartsWith("B")                    
                //select u;          // Query for the unicorn named Binky   

                //                // Add a food category              
                //                var food = new pcAuditLog
                //                { 
                //                    CategoryId = "FOOD", Name = "Foods" 
                //                };
                //                db.pcAuditLog.Add(food);
                //                int recordsAffected = db.SaveChanges();
                //                objLog.WriteLine("Saved {0} entities to the database, press any key to exit.",recordsAffected);              
                //                Console.ReadKey();
                //                var food = db.Categories.Find("FOOD"); 
                //if (food == null) { 
                //    food = new Category 
                //    { CategoryId = "FOOD", Name = "Foods" }; 
                //    db.Categories.Add(food);
                //}              
                // Create a new Food product       
                //Console.Write("Please enter a name for a new food: ");
                //var productName = Console.ReadLine();        
                //var product = new Product { 
                //    Name = productName, Category = food
                //};           
                //db.Products.Add(product); 
                //int recordsAffected = db.SaveChanges();  
                //objLog.WriteLine(            
                //    "Saved {0} entities to the database.",recordsAffected);        
                // Query for all Food products using LINQ          
                //var allFoods = from p in db.Products         
                //               where p.CategoryId == "FOOD"  
                //               orderby p.Name         
                //               select p;       
                //objLog.WriteLine("All foods in database:");      
                //foreach (var item in allFoods)             {     
                //    objLog.WriteLine(" - {0}", item.Name);      
                //}          
                //objLog.WriteLine("Press any key to exit."); 
                //Console.ReadKey(); 

                //using (var context = new UnicornsContext()) {     
                // Query for all unicorns with names starting //with B     
                //                var unicorns = from u in context.Unicorns                    
                //                               where u.Name.StartsWith("B")                    
                //                               select u;          // Query for the unicorn named Binky     
                //                var binky = context.Unicorns                     
                //                    .Where(u => u.Name == "Binky")
                //                    .FirstOrDefault(); }

                //using (var context = new UnicornsContext())
                // {   
                //  // Will hit the database   
                //  var unicorn = context.Unicorns.Find(3);   
                //   // Will return the same instance without hitting the database   
                //  var unicornAgain = context.Unicorns.Find(3);  
                //    context.Unicorns.Add(new Unicorn { Id = -1 });    
                //  // Will find the new unicorn even though it does not exist in the database     
                //var newUnicorn = context.Unicorns.Find(-1);     
                // // Will find a castle which has a string primary key     
                //var castle = context.Castles.Find("The EF Castle"); 
                //}

                //using (var context = new UnicornsContext()) { 
                //var lady = context.LadiesInWaiting.Find(3, "The EF Castle"); 
                //}

                // Add a new princess by setting a reference from a tracked unicorn
                //var unicorn = context.Unicorns.Find(1);  
                //unicorn.Princess = new Princess { Name = "Belle" };  
                // Add a new unicorn by adding to the collection of a tracked princess
                //var princess = context.Princesses.Find(2);  
                //princess.Unicorns.Add(new Unicorn { Name = "Franky" }); 

                //var existingUnicorn = GetMyExistingUnicorn();  
                //    using (var context = new UnicornsContext()) {    
                //        context.Unicorns.Attach(existingUnicorn);   
                //        // Do some more work...     
                //        context.SaveChanges(); 
                //    }

                //        //public void InsertOrUpdate(DbContext context, Unicorn unicorn) { 
                //    context.Entry(unicorn).State = unicorn.Id == 0 ?  EntityState.Added : EntityState.Modified;
                //    context.SaveChanges(); 
                //}

                //using (var context = new UnicornsContext()) {     
                //var unicorn = context.Unicorns.Find(3);      
                //// Read the current value of the Name property     
                //string currentName1 = context.Entry(unicorn).Property(u => u.Name).CurrentValue; 
                //     // Set the Name property to a new value    
                // context.Entry(unicorn).Property(u => u.Name).CurrentValue = "Franky";
                //      // Read the current value of the Name property using a   
                //  // string for the property name   
                //  object currentName2 = context.Entry(unicorn).Property("Name").CurrentValue; 
                //     // Set the Name property to a new value using a  
                //   // string for the property name  
                //   context.Entry(unicorn).Property("Name").CurrentValue = "Squeaky";
                // } 

                //var lady = context.LadiesInWaiting.Find(1, "The EF Castle");     
                // // Read the current value of an unmapped property   
                //  var name1 = context.Entry(lady).Property(p => p.Name).CurrentValue;  
                //    // Use a string to specify the property name   
                //  var name2 = context.Entry(lady).Property("Name").CurrentValue; 

                //using (var context = new UnicornsContext()) {
                //// Load all princesses and related unicorns
                //var princesses1 = context.Princesses
                //.Include(p => p.Unicorns)
                //.ToList();
                //// Load one princess and her related unicorns
                //var princess1 = context.Princesses
                //.Where(p => p.Name == "Cinderella")
                //.Include(p => p.Unicorns)                         .FirstOrDefault();
                //// Load all princesses and related unicorns using a string
                //// to specify the relationship
                //var princesses2 = context.Princesses
                //.Include("Unicorns")
                //.ToList();
                //// Load one princess and her related unicorns using a string
                //// to specify the relationship
                //var princess2 = context.Princesses
                //.Where(p => p.Name == "Cinderella")
                //.Include("Unicorns")
                //.FirstOrDefault(); }

                //using (var context = new UnicornsContext()) {
                //// Load all castles, all related ladies-in-waiting, and all related
                //// princesses
                //var castles1 = context.Castles
                //.Include(c => c.LadiesInWaiting.Select(b => b.Princess))
                //.ToList();
                //// Load all unicorns, all related princesses, and all related ladies
                //var unicorns1 = context.Unicorns
                //.Include(u => u.Princess.LadiesInWaiting)
                //.ToList();
                //// Load all castles, all related ladies, and all related princesses
                //// using a string to specify the relationships
                //var castles2 = context.Castles
                //.Include("LadiesInWaiting.Princess")
                //.ToList();
                //// Load all unicorns, all related princesses, and all related ladies
                //// using a string to specify the relationships
                //var unicorns2 = context.Unicorns
                //.Include("Princess.LadiesInWaiting")
                //.ToList();
                //}

                //using (var context = new UnicornsContext()) {
                //var princess = context.Princesses.Find(1);
                //// Load the unicorns starting with B related to a given princess
                //context.Entry(princess)
                //.Collection(p => p.Unicorns)
                //.Query()
                //.Where(u => u.Name.StartsWith("B"))
                //.Load();
                //// Load the unicorns starting with B related to a given princess
                //// using a string to specify the relationship
                //context.Entry(princess)
                //.Collection("Unicorns")
                //.Query().Cast<Unicorn>()
                //.Where(u => u.Name.StartsWith("B"))
                //.Load();
                //}

                //get count of rows
                //using (var context = new UnicornsContext()) {
                //var princess = context.Princesses.Find(1);
                //// Count how many unicorns the princess owns
                //var unicornHaul = context.Entry(princess)
                //.Collection(p => p.Unicorns)
                //.Query()
                //.Count(); }

                //using (var context = new UnicornsContext()) {
                //// Load all unicorns from the database into the context
                //context.Unicorns.Load();
                //// Add a new unicorn to the context
                //context.Unicorns.Add(new Unicorn { Name = "Linqy" });
                //// Mark one of the existing unicorns as Deleted
                //context.Unicorns.Remove(context.Unicorns.Find(1));
                //// Loop over the unicorns in the context.
                //objLog.WriteLine("In Local: ");
                //foreach (var unicorn in context.Unicorns.Local)     {
                //objLog.WriteLine("Found {0}: {1} with state {2}",
                //unicorn.Id, unicorn.Name,
                //context.Entry(unicorn).State);     }
                //// Perform a query against the database.
                //objLog.WriteLine("" + Environment.NewLine + "In DbSet query: ");
                //foreach (var unicorn in context.Unicorns)     {
                //objLog.WriteLine("Found {0}: {1} with state {2}",
                //unicorn.Id, unicorn.Name,
                //context.Entry(unicorn).State);     }
                //}


                //using (var context = new UnicornsContext()) {
                //bool saveFailed;
                //do
                //{
                //saveFailed = false;
                //var unicorn = context.Unicorns.Find(1);
                //unicorn.Name = "Franky";
                //try         {
                //context.SaveChanges();
                //}
                //catch (DbUpdateConcurrencyException ex)
                //{
                //saveFailed = true;
                //// Update the values of the entity that failed to save
                //// from the store
                //ex.Entries.Single().Reload();
                //}
                //} while (saveFailed);
                //}


                //using (var context = new UnicornsContext()) {
                //bool saveFailed;
                //var unicorn = context.Unicorns.Find(1);
                //unicorn.Name = "Franky";
                //do     {
                //saveFailed = false;
                //try
                //{
                //context.SaveChanges();
                //}
                //catch (DbUpdateConcurrencyException ex)         {
                //saveFailed = true;
                //// Update original values from the database
                //var entry = ex.Entries.Single();
                //entry.OriginalValues.SetValues(entry.GetDatabaseValues());
                //}
                //} while (saveFailed);
                //}


                //using (var context = new UnicornsContext()) {
                //bool saveFailed;
                //var unicorn = context.Unicorns.Find(1);
                //unicorn.Name = "Franky";
                //do     {
                //saveFailed = false;
                //try         {
                //context.SaveChanges();
                //}
                //catch (DbUpdateConcurrencyException ex)         {
                //saveFailed = true;
                //// Get the current entity values and the values in the database
                //var entry = ex.Entries.Single();
                //var currentValues = entry.CurrentValues;
                //var databaseValues = entry.GetDatabaseValues();
                //// Choose an initial set of resolved values. In this case we
                //// make the default be the values currently in the database.
                //var resolvedValues = databaseValues.Clone();
                //// Have the user choose what the resolved values should be
                //HaveUserResolveConcurrency(currentValues, databaseValues,
                //resolvedValues);
                //// Update the original values with the database values and
                //// the current values with whatever the user choose.
                //entry.OriginalValues.SetValues(databaseValues);
                //entry.CurrentValues.SetValues(resolvedValues);
                //}
                //} while (saveFailed);
                //}
                //public void HaveUserResolveConcurrency(DbPropertyValues currentValues,                 
                //DbPropertyValues databaseValues,
                //    DbPropertyValues resolvedValues) { 
                // Show the current, database, and resolved values to the user and have  
                // them edit the resolved values to get the correct resolution. }

                //using (var context = new UnicornsContext()) { 
                //var unicorns = context.Unicorns.SqlQuery("select * from Unicorns").ToList(); 
                //}
                //var unicornNames = context.Database.SqlQuery<string>("select Name from Unicorns").ToList(); 
                //context.Database.ExecuteSqlCommand("update Unicorns set Name = 'Franky' where Name = 'Beepy'");  

                //using (var context = new UnicornsContext()) {    
                // Query for all unicorns without tracking them     
                //var unicorns1 = context.Unicorns.AsNoTracking();      
                // Query for some unitcorns without tracking them     
                //var unicorns2 = context.Unicorns                         
                //    .Where(u => u.Name.EndsWith("ky"))                         
                //    .AsNoTracking()                         
                //    .ToList(); 
                //} 

                //In a sense Load and AsNoTracking are opposites. 
                //Load executes a query and tracks the results in the context without returning them.
                //AsNoTracking executes a query and returns the results without tracking them in the context.

                //using (var context = new UnicornsContext()) {  
                //   try     { 
                //        context.Configuration.AutoDetectChangesEnabled = false; 
                //         // Make many calls in a loop     
                //    foreach (var unicorn in myUnicorns)         {   
                //          context.Unicorns.Add(unicorn);      
                //   }  
                //   }     finally     {  
                //       context.Configuration.AutoDetectChangesEnabled = true;     }
                // }

            }

        }


    }
}



